<!-- FilePreview.vue -->
<template>
  <div class="file-preview-overlay" v-if="fileVisible">
    <div class="file-preview-container">
      <button class="close-btn" @click="handleClose">×</button>

      <!-- 图片预览 -->
      <div v-if="isImage" class="preview-content preview-content-img">
        <img :src="fileUrl" :alt="fileName" />
      </div>

      <!-- PDF预览 -->
      <div v-else-if="isPdf" class="preview-content preview-content-pdf">
        <VuePdfEmbed v-if="fileUrl" class="pdf-viewer" :source="fileUrl" />
      </div>

      <!-- word文件预览 -->
      <div v-else-if="isWord" class=" preview-content preview-content-word">
        <div class="word-wrapper" ref="wordFilePreview"></div>
      </div>

      <!-- excel文件预览 -->
      <div v-else-if="isExcel" class="preview-content preview-content-excel">
        <VueOfficeExcel :src="fileUrl" />
      </div>

      <!-- ppt文件预览 -->
      <div v-else-if="isPpt" class="preview-content preview-content-excel">
        <canvas ref="pptContainer" class="ppt-container"></canvas>
      </div>

      <!-- 视频 -->
      <div v-else-if="isVideo" class="preview-content preview-content-excel">
        <video ref="mediaElement" :src="fileUrl" controls class="media-element"></video>
      </div>



      <!-- 其他文件类型 -->
      <div v-else class="unsupported-type">
        <p>不支持预览此文件类型</p>
        <a v-if="fileUrl" :href="fileUrl" download>下载文件</a>
      </div>
    </div>
  </div>
</template>
<script>

</script>

<script setup>
import { computed, ref, onMounted, nextTick } from 'vue'
import VuePdfEmbed from 'vue-pdf-embed';  // pdf预览
import { renderAsync } from 'docx-preview'; // word预览
// excel预览
import VueOfficeExcel from '@vue-office/excel'
import '@vue-office/excel/lib/index.css'
// ppt预览

// props数据
const props = defineProps({
  fileParams: {
    type: [String, File],
    required: true
  },
  fileName: {
    type: String,
    default: ''
  },
  fileVisible: {
    type: Boolean,
    default: false
  }

})
const emit = defineEmits(['close'])

// 文件转化url
const fileUrl = computed(() => {
  if (typeof props.fileParams === 'string') {
    return props.fileParams
  } else if (props.fileParams instanceof File) {
    return URL.createObjectURL(props.fileParams)
  }
  return ''
})
console.log(fileUrl.value);


// 获取文件类型
const fileExtension = computed(() => {
  const name = props.fileName || (props.fileParams instanceof File ? props.fileParams.name : '')

  if (!name) return ''
  const parts = name.split('.')

  const partsGs = parts.length > 1 ? parts.pop().toLowerCase() : ''
  if (!partsGs) { console.log('未曾获取到文件类型，请检查文件名或文件类型'); }

  return partsGs
})
console.log(fileExtension.value);



// 是否为图片
const isImage = computed(() => {
  return ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'].includes(fileExtension.value)
})

// 是否为pdf
const isPdf = computed(() => fileExtension.value === 'pdf')


// 是否为word
const wordFilePreview = ref(null)
const isWord = computed(() => {
  return ['doc', 'docx'].includes(fileExtension.value)
})
console.log(isWord.value);

// 是否为excel
const excelData = ref(null)
const isExcel = computed(() => {
  return ['xls', 'xlsx'].includes(fileExtension.value)
})

// 是否为ppt
const pptContainer = ref(null)
const isPpt = computed(() => {
  return ['ppt', 'pptx'].includes(fileExtension.value)
})

// 是否为ppt
const isVideo = computed(() => {
  return ['MP3', 'mp3'].includes(fileExtension.value)
})

// 关闭回调
const handleClose = () => {
  emit('close')
}

onMounted(async () => {
  try {
    // excel处理
    if (isExcel.value) {
      await nextTick();
      const reader = new FileReader();
      reader.onload = (e) => {
        const data = new Uint8Array(e.target.result);
        const workbook = XLSX.read(data, { type: 'array' });
        const firstSheetName = workbook.SheetNames[0];
        const worksheet = workbook.Sheets[firstSheetName];
        excelData.value = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
      };
      const response = await fetch(fileUrl.value);
      const buffer = await response.arrayBuffer();
      reader.readAsArrayBuffer(buffer);
    }

    // word文件处理
    if (isWord.value) {
      await nextTick();
      const response = await fetch(fileUrl.value);
      const buffer = await response.arrayBuffer();
      await renderAsync(buffer, wordFilePreview.value);
    }

    // ppt文件处理
    if (isPpt.value) {
    }
  } catch (error) {
    console.log(error);
  }
});

</script>

<style lang="scss" scoped>
.file-preview-overlay {
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.7);
  display: flex;
  justify-content: center;
  align-items: center;

  .file-preview-container {
    border-radius: 8px;
    width: 100%;
    height: 100%;
    position: relative;
    padding: 20px 25px;

    .close-btn {
      position: absolute;
      top: 0;
      right: 6px;
      background: none;
      border: none;
      font-size: 24px;
      cursor: pointer;
      z-index: 10;
    }

    .preview-content {
      width: 100%;
      height: 100%;
      display: flex;
      justify-content: center;
      align-items: center;

      img {
        width: 100%;
        height: 100%;
        object-fit: contain;
      }

      .pdf-viewer,
      .docx-container {
        width: 100%;
        height: 100%;
      }
    }

    .preview-content-img,
    .preview-content-pdf {
      overflow: auto;
    }

    .preview-content-word {
      .word-wrapper {
        width: 100%;
        height: 100%;

        :deep(.docx-wrapper) {
          width: 100%;
          height: 100%;
          overflow: auto;
          align-items: flex-start;
          background-color: transparent;
        }
      }
    }

    .preview-content-excel {
      :deep(.vue-office-excel) {
        width: 100%;
      }
    }

    .unsupported-type {
      padding: 40px;
      text-align: center;
    }

    a {
      display: inline-block;
      margin-top: 20px;
      padding: 8px 16px;
      background-color: #409eff;
      color: white;
      text-decoration: none;
      border-radius: 4px;
    }
  }
}
</style>